package cn.exrick.xboot.modules.ApprovalInfo.controller;
import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.constant.SecurityConstant;
import cn.exrick.xboot.common.timeTask.approval.StartApprovalThread;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResponseUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.utils.jiuqi.utils.DateUtile;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.ApprovalInfo.entity.ApprovalInfo;
import cn.exrick.xboot.modules.ApprovalInfo.service.IApprovalInfoService;
import cn.exrick.xboot.modules.ApprovalInfo.utils.ApprovalInfoUtils;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author njp
 */
@Slf4j
@RestController
@Api(description = "审批信息表管理接口")
@RequestMapping("/xboot/approvalInfo")
@Transactional
public class ApprovalInfoController {

    @Autowired
    private IApprovalInfoService iApprovalInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //private ApprovalInfoUtils approvalInfoUtils = new ApprovalInfoUtils();

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "通过id获取")
    public Result<ApprovalInfo> get(@PathVariable String id) {

        ApprovalInfo approvalInfo = iApprovalInfoService.getById(id);
        return new ResultUtil<ApprovalInfo>().setData(approvalInfo);
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取全部数据")
    public Result<List<ApprovalInfo>> getAll() {

        List<ApprovalInfo> list = iApprovalInfoService.list();
        return new ResultUtil<List<ApprovalInfo>>().setData(list);
    }

    @RequestMapping(value = "/getByPage", method = RequestMethod.GET)
    @ApiOperation(value = "分页获取")
    public Result<IPage<ApprovalInfo>> getByPage(@ModelAttribute PageVo page) {

        IPage<ApprovalInfo> data = iApprovalInfoService.page(PageUtil.initMpPage(page));
        return new ResultUtil<IPage<ApprovalInfo>>().setData(data);
    }

    @RequestMapping(value = "/insertOrUpdate", method = RequestMethod.POST)
    @ApiOperation(value = "编辑或更新数据(审批员审批)")
    public Result<ApprovalInfo> saveOrUpdate(@ModelAttribute ApprovalInfo approvalInfo,HttpServletRequest request) {

        String headerToken = request.getHeader(SecurityConstant.HEADER);
        String v=null;
        v = stringRedisTemplate.opsForValue().get(SecurityConstant.TOKEN_PRE + headerToken);
        if(StrUtil.isBlank(v)){
            //进行判断app
            v = stringRedisTemplate.opsForValue().get(SecurityConstant.APP_TOKEN_PRE + headerToken);

            if (StrUtil.isBlank(v)){
                return new ResultUtil<ApprovalInfo>().setErrorMsg(401,"登录已失效，请重新登录!");
            }
        }
        /*if (v == null || v == ""){
            return new ResultUtil<ApprovalInfo>().setErrorMsg(401,"登录已失效，请重新登录!");
        }*/

        ApprovalInfo Info = iApprovalInfoService.getById(approvalInfo.getId());
        if (CommonConstant.APPROVAL_AGREE == Info.getApprovalStatus() || CommonConstant.APPROVAL_DISAGREE == Info.getApprovalStatus()) {
            return new ResultUtil<ApprovalInfo>().setErrorMsg("该数据已被其他审批员审批");
        }else if(CommonConstant.APPROVAL_TIMEOUT == Info.getApprovalStatus()){
            return new ResultUtil<ApprovalInfo>().setErrorMsg("审批已超时");
        }
        Date date = new Date();
        //approvalInfo.setCreateTime(date);
        approvalInfo.setUpdateTime(date);
        //添加审批时间
        approvalInfo.setApprovalTime(date);
        if (iApprovalInfoService.saveOrUpdate(approvalInfo)) {
            //审批结束后后台通过长连接向前端发送审批结果
            Boolean aBoolean = new ApprovalInfoUtils().sendApprovalResult(approvalInfo);
            return new ResultUtil<ApprovalInfo>().setData(approvalInfo);
        }
        return new ResultUtil<ApprovalInfo>().setErrorMsg("操作失败");
    }

    @RequestMapping(value = "/submitApprovalInfo", method = RequestMethod.POST)
    @ApiOperation(value = "提交审批")
    public Result<ApprovalInfo> submitApprovalInfo(@ModelAttribute ApprovalInfo approvalInfo) {
        ApprovalInfoUtils approvalInfoUtils = new ApprovalInfoUtils();
        approvalInfo.setMsg(CommonConstant.APP_CONTENT);
        approvalInfo.setUsername(CommonConstant.PARAM_USERNAME);
        Date date = new Date();
        approvalInfo.setCreateTime(date);
        approvalInfo.setUpdateTime(date);
        //在提交审批之前要将其余审批状态设置为不可用状态
        approvalInfoUtils.updateStatus();
        //目前超时时间设置为一小时之后
        approvalInfo.setExpirationTime(DateUtile.getDate(CommonConstant.APPROVAL_END_TIME));
        if (iApprovalInfoService.saveOrUpdate(approvalInfo)) {
            //1.在超级管理员提交审批成功后向审批员推送信息：使用websocket向pc端推送新审批数据2.使用极光推送向APP推送新审批数据
            ApprovalInfo approval = iApprovalInfoService.getById(approvalInfo.getId());
            new ApprovalInfoUtils().sendApprovalInfo(approval);

            //审批提交后开启一个线程用来操作该数据超时后的状态监控（并做状态修改）
            StartApprovalThread.startThread();
            return new ResultUtil<ApprovalInfo>().setData(approvalInfo);
        }
        return new ResultUtil<ApprovalInfo>().setErrorMsg("操作失败");
    }

    @RequestMapping(value = "/delByIds/{ids}", method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过id删除")
    public Result<Object> delAllByIds(@PathVariable String[] ids) {

        for (String id : ids) {
            iApprovalInfoService.removeById(id);
        }
        return new ResultUtil<Object>().setSuccessMsg("批量通过id删除数据成功");
    }


    @RequestMapping(value = "/selectApprovalInfo", method = RequestMethod.GET)
    @ApiOperation(value = "查询待审批数据")
    public Result<List<ApprovalInfo>> selectApprovalInfo(@ModelAttribute ApprovalInfo approvalInfo) {
        log.info("调用接口;selectApprovalInfo()查询待审批未过期ApprovalStatus=3的数据");
        approvalInfo.setNowTime(new Date());
        approvalInfo.setApprovalStatus(CommonConstant.APPROVAL_INIT);//3:待审批
        List<ApprovalInfo> approvalInfos = iApprovalInfoService.selectApprovalInfo(approvalInfo);
        return new ResultUtil<List<ApprovalInfo>>().setData(approvalInfos);
    }

    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    @ApiOperation(value = "获取审批数据列表按时间倒序排列")
    public Result<IPage<ApprovalInfo>> selectAll(@ModelAttribute Page page, @ModelAttribute ApprovalInfo approvalInfo, HttpServletRequest request) {

        String headerToken = request.getHeader(SecurityConstant.HEADER);
        String v = stringRedisTemplate.opsForValue().get(SecurityConstant.APP_TOKEN_PRE + headerToken);
        if (v == null || v == ""){
            return new ResultUtil<IPage<ApprovalInfo>>().setErrorMsg(401,"登录已失效，请重新登录!");
        }

        log.info("调用接口;selectAll()获取审批数据列表按时间倒序排列");
        IPage<ApprovalInfo> approvalInfos = iApprovalInfoService.selectApprovalInfo(page, approvalInfo);
        return new ResultUtil<IPage<ApprovalInfo>>().setData(approvalInfos);
    }


}
